package com.mc.lp.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.mc.lp.database.dao.IRolePermissionDAO;
import com.mc.lp.database.dao.IUserDAO;
import com.mc.lp.database.entity.PermissionEntity;
import com.mc.lp.database.entity.UserEntity;
import com.mc.lp.database.entity.helper.UserEntityHelper;
import com.mc.lp.service.MicroCampusAbstractService;
import com.mc.lp.service.UserService;
import com.mc.lp.shared.vo.UserVO;
 
@Service
public class UserServiceImpl extends MicroCampusAbstractService<UserServiceImpl> implements UserService{
	
	@Resource
	private IUserDAO userDAO;
	
	@Resource
	private IRolePermissionDAO rolePermissionDao;
	
	@Resource
	private UserEntityHelper userEntityHelper;
	
	@Transactional
	public UserVO getUserByUserName(String userName) {
		
		LOG.debug("Fetching user with username :"+ userName);
		List<UserEntity> userList= userDAO.findByProperty("userName", userName);
		if(!CollectionUtils.isEmpty(userList)){
			UserEntity entity = userList.get(0);
			LOG.debug("User name found, returning true :"+entity.getUserName());
			//get the granted permission for the user and create value object from them
			Set<PermissionEntity> permissions = rolePermissionDao.resolvePermissionsByRoleId(entity.getRoles(),new HashSet<PermissionEntity>());
			LOG.debug("Permissions found :"+ permissions);
			return userEntityHelper.getVO(entity,userEntityHelper.getStringListFromPermissions(permissions));
		}else{
			LOG.debug("User name does not exists");
		}
		return null;
	}
	
}
